// https://www.lintcode.com/problem/similar-rgb-color/

public class Solution {
    /**
     * @param color: the given color
     * @return: a 7 character color that is most similar to the given color
     */
    public String similarRGB(String color) {
        // Write your code here
        // 可以用二分法优化，还有0x??一定是17的倍数，可以找离它最近的17的倍数比较。
        StringBuilder sb = new StringBuilder();
        sb.append('#');
        for (int i = 1; i < 7; i += 2) {
            String c = findNearest(color.charAt(i), color.charAt(i + 1));
            if (c.equals("0")) {
                sb.append('0');
            }
            sb.append(c);
        }
        return sb.toString();
    }
    
    protected String findNearest(char c1, char c2) {
        int ret = 0, diff = 0x100;
        int[] colors = new int[]{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
        int color = hext2Int(c1, c2);
        System.out.println(color);
        for (int _color : colors) {
            if (Math.abs((int)(_color - color)) < diff) {
                diff = Math.abs(_color - color);
                ret = _color;
            }
        }
        return Integer.toHexString(ret);
    }
    
    protected int hext2Int(char c1, char c2) {
        StringBuilder sb = new StringBuilder();
        sb.append(c1);
        sb.append(c2);
        return Integer.parseInt(sb.toString(), 16);
    }
}